import { useState, useEffect, useRef } from 'react';
import { Card, Col, Row, message, Button } from 'antd';
import {
    SettingOutlined, PlayCircleOutlined, ExceptionOutlined, VerticalAlignBottomOutlined,
    IssuesCloseOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useOutletContext } from 'react-router-dom';

import { taillog, startPost, stopPost } from "@/api/console"
import { getState } from '@/api/common';
import './index.scss';

// 提取常量
const INITIAL_INFO = {
    "ad_serial": "",
    "ipconfig": { "post": "", "ip": "", "cid": "" },
    "cid": "", "ip": "", "post": "", "msg": "",
    "serial_state": "", "state": "", "version": ""
};

function Console(props) {
    const { onEvent } = useOutletContext();
    const { t } = useTranslation();
    const [info, setInfo] = useState(INITIAL_INFO);
    const [msg, setMsg] = useState({});

    // 提取重复的卡片标题渲染
    const renderCardTitle = (icon, titleKey) => (
        <div className='title'>
            {icon}
            <span className="tit">{t(titleKey)}</span>
        </div>
    );

    // 提取运行状态显示
    const renderRunningStatus = () => {
        if (info.state === 'on') return t("header.running");
        if (info.state === 'off') return t("header.stopped");
        return t("header.unknown");
    };

    function getLoad() {
        getState().then(res => {
            setInfo(res[0]);
            onEvent(res[0]);
        });
    }

    function timeFunc() {
        taillog().then(res => {
            setMsg(res)
        });
        getLoad();
    }

    function start() {
        startPost().then(res => {
            if (info.state === 'on') {
                message.success(t('message.console.running'));
            } else {
                message.success(t('message.console.start'))
            }
            getLoad();
        })
    }

    function stop() {
        stopPost().then(res => {
            message.success(t('message.console.stop'))
            getLoad();
        })
    }

    useEffect(() => {
        timeFunc();
        const intervalId = setInterval(timeFunc, 2000);
        return () => clearInterval(intervalId);
    }, [])

    return (
        <div className="console-container">
            <div className="row-a1">
                <div className="left">
                    {/* 系统概览 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<IssuesCloseOutlined style={{ color: '#08c' }} />, "console.systemOverview")}>
                            <div className="list">
                                <div className="li">
                                    <div className="tit">{t("console.systemStatus")}</div>
                                    <div className={"txt " + info.state}>{renderRunningStatus()}</div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t("console.shelfNumber")}</div>
                                    <div className="txt">{info.ipconfig.cid}</div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t("console.serverConnection")}</div>
                                    <div className="txt light">{info.ipconfig.post}</div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t("console.configStatus")}</div>
                                    <div className="txt">{t("console.loaded")}</div>
                                </div>
                            </div>
                        </Card>
                    </div>

                    {/* 控制系统 */}
                    <div className="con-a2">
                        <Card title={renderCardTitle(<SettingOutlined style={{ color: '#08c' }} />, "console.controlSystem")} className="card-a1">
                            <Row>
                                <Col span={24}>
                                    <div className="start-btn btn" onClick={start}>
                                        <PlayCircleOutlined />
                                        <span>{t("console.startSystem")}</span>
                                    </div>
                                    <div className="pause-btn btn" onClick={stop}>
                                        <PlayCircleOutlined />
                                        <span>{t("console.stopSystem")}</span>
                                    </div>
                                </Col>
                            </Row>
                        </Card>
                    </div>

                    {/* 日志管理 */}
                    <div className="con-a3">
                        <Card title={renderCardTitle(<ExceptionOutlined style={{ color: '#08c' }} />, "console.logManagement")}>
                            <Button href="/download/" type="primary" className="download-btn" icon={<VerticalAlignBottomOutlined />}>
                                {t("console.downloadLogs")}
                            </Button>
                        </Card>
                    </div>
                </div>

                <div className="right">
                    {/* 系统信息 */}
                    <div className="con-a4">
                        <Card title={renderCardTitle(<ExclamationCircleOutlined style={{ color: '#08c' }} />, 'console.systemInfo')}>
                            <div className="list">
                                <div className="li">
                                    <div className="tit">{t("console.serverAddress")}</div>
                                    <div className="txt">{info.ipconfig.ip}</div>
                                </div>
                            </div>
                        </Card>
                    </div>

                    {/* 实时日志 */}
                    <div className="con-a5">
                        <Card title={renderCardTitle(<ExceptionOutlined style={{ color: '#08c' }} />, "console.realtimeLogs")}>
                            <div className="list">
                                <div className='li' dangerouslySetInnerHTML={{ __html: msg.msg }} />
                            </div>
                        </Card>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Console;